package org.codeasy.site.devtools.ibatissqlformat.action;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.codeasy.ceutils.string.StringUtil;
import org.codeasy.site.common.dto.DataResult;
import org.codeasy.site.common.utils.WebUtil;
import org.codeasy.site.devtools.ibatissqlformat.service.IbatisSqlFormatService;

import com.opensymphony.xwork2.ActionSupport;

public class IbatisSqlFormatAction extends ActionSupport {
	
	private static Logger logger = Logger.getLogger(IbatisSqlFormatAction.class);

	private String sqlsAndParams;
	
	private IbatisSqlFormatService ibatisSqlFormatService;
	
	private WebUtil webUtil;
	
	private static Long MAX_DEAL_TEXT_COUNT = 50000L;
	
	

	public void formatSql() throws Exception {
		
		log("SqlsAndParams is ->" + sqlsAndParams);
		HttpServletResponse response = webUtil.getResponse();
		DataResult dr = new DataResult();
		
		if (StringUtil.isBlank(sqlsAndParams)) {
			response.getWriter().write("");
			dr.setErrorFlag(1);
			dr.setErrorMsg("请先录入SQL和参数");
		} else if (checkData(sqlsAndParams,dr)) {
			List<String> resultList;
			try {
				resultList = ibatisSqlFormatService.format(sqlsAndParams);
				StringBuffer sb = new StringBuffer();
				for (int i = 0 ; i < resultList.size(); i++) {
					sb.append(resultList.get(i));
				}
				dr.setResultMsg(sb.toString());
				dr.getResultList().addAll(resultList);
				log("this format result is -> " + sb.toString());
			} catch (Exception e) {
				logger.error("在组装SQL时候发生异常",e);
				dr.setErrorFlag(1);
				dr.setErrorMsg(e.getMessage());
			}
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("dataResult", dr);
		String jsonStr = jsonObject.toString();
		log("JSON result is ->" + jsonStr);
		response.getWriter().write(jsonStr);
	}
	
	public boolean checkData(String inputData, DataResult dr) {
		if (inputData.length() > MAX_DEAL_TEXT_COUNT) {
			dr.setErrorFlag(1);
			dr.setErrorMsg("输入的字符数共" + inputData.length() + "个,大于系统目前最大允许处理的字符数" + MAX_DEAL_TEXT_COUNT + ",请分批次提交大SQL");
			return false;
		}
		return true;
	}

	public void setSqlsAndParams(String sqlsAndParams) {
		this.sqlsAndParams = sqlsAndParams;
	}



	public void setIbatisSqlFormatService(IbatisSqlFormatService ibatisSqlFormatService) {
		this.ibatisSqlFormatService = ibatisSqlFormatService;
	}

	public void setWebUtil(WebUtil webUtil) {
		this.webUtil = webUtil;
	}
	
	
	
	void log(String log) {
		if (logger.isInfoEnabled()) {
			logger.info(log);
		}
	}
	
	

}
